<template>
	<!-- <view class="container"> -->
	<view class="margin-top-sm padding-lr-xs">
		<view class="bg-white light radius-lg shadow-blur">
			<view class="balance-title" style="text-align: center;">我的余额(元)</view>
			<view class="balance-amount" style="text-align: center;">{{balance}}</view>
			<view class="buttons">
				<button class="recharge-btn" open-type="contact" data-target="ChooseModal" @tap="showModal">充值</button>
				<!-- <button class="withdraw-btn" open-type="contact">提现</button> -->
			</view>
		</view>
	</view>

	<!-- <view class="margin-top-sm padding-lr-xs">
    <view class="bg-white light radius-lg shadow-blur">
      <view class="balance-title" style="text-align: center;">我的余额(元)</view>
      <view class="balance-amount" style="text-align: center;">100.00</view>
      <view class="buttons">
        <button class="recharge-btn" open-type="contact">充值</button>
        <button class="withdraw-btn" open-type="contact">提现</button>
      </view>
    </view>
  </view> -->

	<!-- <view class="coupon-info">
    <view class="coupon-title">优惠券</view>
    <scroll-view class="coupon-list" scroll-x>
      <view class="coupon-item" wx:for="{{coupons}}" wx:key="index">
        {{item.name}}
      </view>
    </scroll-view>
  </view> -->
	<view class="cu-bar margin-lr-xs margin-top-sm grid col-4 no-border bg-white radius-lg-top">
		<view class="action" style="width: 320rpx;">
			<text class="text-xl text-black" style="position: relative; right: 50rpx; font-weight: 600;">余额变动明细</text>
		</view>
		<!-- <view class="action">
      <text class="" style="position: relative; left: 50rpx;">全部<text class="cuIcon-right"></text></text>
    </view> -->
	</view>
	<view class="cu-list bg-white no-border text-black margin-lr-xs padding-bottom radius-lg-bottom"
		style="padding-bottom: 5rpx;">
		<view class="cu-item" v-for="item in recordDetails"
			style="padding-top: 10rpx; padding-left: 20rpx; padding-right: 20rpx; height: 100rpx; border-top: 1rpx solid #EBEBEB;"
			@tap="toRecordDetail(item)">
			<view class="flex" style="justify-content: space-between;">
				<view class="padding-xs" style="align-items: center; display: flex;">
					<view style="font-size: 31rpx; line-height: 0; font-weight: 400;">{{item.reason}}</view>
				</view>
				<view class="padding-xs"
					style="align-items: center; display: flex; position: relative; left: 0%; right: 20%;">
					<view style="font-size: 28rpx; font-weight: 100; line-height: 0; color: #5E6168;">{{item.status}}
					</view>
				</view>
				<view class="padding-xs" style="display: flex; flex-direction: column; justify-content: space-between;">
					<view style="font-weight: bold; text-align: center; font-size: 30rpx;">{{item.transactionAmount}}
					</view>
					<view class="date" style="color: #868686;">{{item.transactionTime}}</view>
				</view>
			</view>
		</view>
	</view>

	<!-- 充值金额模态框 -->

	<view class="cu-modal bottom-modal" :class="modalName=='ChooseModal'?'show':''" id="1" @tap="handleModalClick"
		style="z-index: 1;">
		<view class="cu-dialog" @tap.stop="">
			<view class="cu-bar bg-white">
				<view class="action text-blue" @tap="hideModal()">取消</view>
				<view class="action text-green" @tap="() => prepareRecharge(getSelectedValue())">确定</view>
			</view>
			<view class="grid col-3 padding-sm">
				<view v-for="(item,index) in checkbox" class="padding-xs" :key="index">
					<button class="cu-btn orange lg block" :class="item.checked?'bg-orange':'line-orange'"
						@tap="ChooseCheckbox" :data-value="item.value"> {{item.name}}
					</button>
				</view>
			</view>
		</view>


		<!-- 充值确认框 -->
		<view v-if="Boolean(rechargeWindow)" class="overlay" @tap="closeRechargePopup()">
			<view class="popup" @tap.stop="">
				<view style="text-align: center; font-size: 35rpx; padding-bottom: 10rpx;">是否完成付款？</view>
				<view class="balance-amount" style="text-align: center;">{{prepareParam.transactionAmount}}元</view>
				<button @click="recharge()" style="margin-top: 20rpx; border: 1rpx solid coral;">确认</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		onLoad,
		onShow
	} from "@dcloudio/uni-app";
	import {
		checkBalance,
		addRechargeRecord,
		selectPayRecord,
		prepareAddRecord
	} from '/pages/mine/api/record.js';
	import {
		forEach
	} from 'lodash';
	import qs from 'qs';
	import { debounce } from 'lodash';
	// 数据定义
	const currentTime = ref('');
	const CustomBar = ref(null);
	const modalName = ref(null);
	// const canConfirm = computed(() => checkbox.value.some(item => item.checked));
	const balance = ref('0.00');
	const userDataString = localStorage.getItem("UserId");
	const userId = ref();
	const rechargeWindow = ref(false);
	const prepareParam = ref({})
	const recordId = ref();
	const recordDetails = ref([{
		id: "",
		accountUserId: "",
		payerUserId: "",
		transactionAmount: "",
		transactionStatus: "",
		transactionTime: "",
		transactionType: "",
		articleId: "",
		status: "",
		reason: "",
	}])
	const checkbox = ref([{
			value: 10.00,
			name: '10.00元',
			checked: false,
			index: 1
		},
		{
			value: 20.00,
			name: '20.00元',
			checked: false,
			index: 2
		},
		{
			value: 30.00,
			name: '30.00元',
			checked: false,
			index: 3
		},
		{
			value: 60.00,
			name: '60.00元',
			checked: false,
			index: 4
		},
		{
			value: 80.00,
			name: '80.00元',
			checked: false,
			index: 5
		},
		{
			value: 100.00,
			name: '100.00元',
			checked: false,
			index: 6
		}
	]);

	// 方法定义
	// 加载当前用户余额
	const loadBalance = async (userId) => {
		console.log("当前用户：" + userId)
		const res = await checkBalance(userId);
		// console.log(res.data);
		balance.value = res.data;
	}

	// 余额充值
	const recharge = async () => {
		const res = await addRechargeRecord(prepareParam.value.recordId);
		rechargeWindow.value = false;
		if (res.data == 3) {
			uni.showToast({
				title: "订单超时",
				duration: 2000,
				icon: 'error',
			})
			return;
		}

		uni.showLoading();
		await setTimeout(function() {
			uni.hideLoading();
			uni.showToast({
				title: "充值成功",
				duration: 1000,
			})
		}, 600);
		loadBalance(userId.value);
		hideModal();
		loadRecords();

	};

	// 加载交易记录
	const loadRecords = async () => {
		const res = await selectPayRecord(userId.value);
		// console.log(res.data);
		recordDetails.value = res.data;
		for (const item of recordDetails.value) {
			switch (item.transactionStatus) {
				case 0:
					item.status = "交易中";
					break;
				case 1:
					item.status = "交易成功";
					break;
				case 2:
					item.status = "交易失败";
					break;
				case 3:
					item.status = "交易取消"
					break;
			}
			switch (item.transactionType) {
				case 1:
					item.reason = "购买文章";
					break;
				case 2:
					item.reason = "余额充值";
			}
			if (item.articleId == null) {
				item.transactionAmount = "+" + item.transactionAmount;
			}
		};
	};

	// 展示模态框
	const showModal = (e) => {
		modalName.value = e.currentTarget.dataset.target;
	};

	// 隐藏模态框
	const hideModal = () => {
		modalName.value = null;
		checkbox.value.forEach(item => (item.checked = false));
		rechargeWindow.value = false;
	}


	// 模态框的确认键
	const prepareRecharge = throttle( async (amount) => {
		// modalName.value = null;  //控制充值金额选择框的显示
		console.log('Selected Value:', amount);
		if (!amount) {
			uni.showToast({
				title: "请选择或输入余额",
				duration: 1500,
				icon: "error",
				position: top
			})
			return;
		}
		rechargeWindow.value = true;
		prepareParam.value.accountUserId = userId.value;
		prepareParam.value.payerUserId = userId.value;
		prepareParam.value.transactionAmount = amount;
		await updateTime();
		prepareParam.value.transactionTime = currentTime.value;
		const res = await prepareAddRecord(prepareParam.value);
		console.log(res.data)
		prepareParam.value.recordId = res.data;
		console.log(prepareParam.value);
		handlePay(prepareParam.value.transactionAmount);
	}, 2000);
	
	function throttle(func, limit) {
	    let inThrottle;
	    return function() {
	        const args = arguments;
	        if (!inThrottle) {
	            func.apply(this, args);
	            inThrottle = true;
	            setTimeout(() => inThrottle = false, limit);
	        }
	    };
	}



	const handlePay = (amount) => {
		const url = 'http://localhost:10011/wallet/alipay/pay';
		const params = {
			outTradeNo: prepareParam.value.recordId,
			subject: '余额充值',
			totalAmount: amount
		};
		console.log(123123)
		window.open(`${url}?${qs.stringify(params)}`);
		// openURL(`${url}?${qs.stringify(params)}`);
	}



	// 获得选择的金额的数值
	const getSelectedValue = () => {
		const selected = checkbox.value.find(item => item.checked);
		return selected ? selected.value : null;
	};

	//选择模态框里的金额
	const ChooseCheckbox = (e) => {
		const value = e.currentTarget.dataset.value;

		checkbox.value.forEach(item => {
			item.checked = false;
		});

		checkbox.value.find(item => item.value === value).checked = true;
	};

	// const chooseCheckbox = item => {
	//   checkbox.value.forEach(i => (i.checked = i === item));
	// };

	// 关闭弹窗
	const closeRechargePopup = () => {
		rechargeWindow.value = false;
		modalName.value = 'ChooseModal';
	};

	// 防止穿透
	const handleModalClick = (e) => {
		// 如果没有弹窗，点击模态框外部关闭模态框
		if (!rechargeWindow.value && e.target.id == 1) {
			hideModal();
		}
	};

	const toRecordDetail = async (recordDetail) => {
		await uni.setStorage({
			key: "recordDetail",
			data: recordDetail
		})
		uni.navigateTo({
			url: '/pages/mine/recordDetail'
		})
	}

	const updateTime = () => {
		const now = new Date();
		const year = now.getFullYear();
		const month = String(now.getMonth() + 1).padStart(2, '0');
		const day = String(now.getDate()).padStart(2, '0');
		const hours = String(now.getHours()).padStart(2, '0');
		const minutes = String(now.getMinutes()).padStart(2, '0');
		const seconds = String(now.getSeconds()).padStart(2, '0');

		currentTime.value = new Date(`${year}-${month}-${day} ${hours}:${minutes}:${seconds}`);
	}


	onShow(() => {
		// 设置定时器每秒更新时间
		// const timerId = setInterval(updateTime, 1000);
		const userData = JSON.parse(userDataString);
		userId.value = userData.data;
		loadBalance(userId.value);
		loadRecords();
	});
	// 在组件卸载时清除定时器
	// clearInterval(timerId);
</script>

<style scoped>
	.popup {
		width: 470rpx;
		background: white;
		padding: 20px;
		border-radius: 8px;
		text-align: center;
		z-index: 1112;
	}

	.overlay {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 1111;
		background: rgba(0, 0, 0, 0.3);
	}

	.date {
		color: #666;
		/* 可以根据需要调整颜色 */
		font-size: 0.8em;
		/* 可以根据需要调整字体大小 */
		text-align: center;
	}

	.container {
		padding: 20rpx;
		box-sizing: border-box;
	}

	.balance-card {
		background-color: #fff;
		border-radius: 10rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.balance-title {
		font-size: 36rpx;
		color: #333;
		margin-bottom: 20rpx;
		padding-top: 15rpx;
	}

	.balance-amount {
		font-size: 56rpx;
		color: black;
		font-weight: bold;
	}

	.buttons {
		display: flex;
		justify-content: space-between;
		margin-top: 20rpx;
		padding-bottom: 20rpx;
	}

	.recharge-btn,
	.withdraw-btn {
		width: 40%;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 40rpx;
		font-size: 32rpx;
	}

	.recharge-btn {
		background-color: coral;
		color: #fff;
	}

	.withdraw-btn {
		background-color: #ebedf0;
		color: #333;
	}

	.coupon-info {
		background-color: #fff;
		border-radius: 10rpx;
		padding: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.coupon-title {
		font-size: 36rpx;
		color: #333;
		margin-bottom: 20rpx;
	}

	.coupon-list {
		white-space: nowrap;
		overflow: auto;
	}

	.coupon-item {
		display: inline-block;
		padding: 10rpx 20rpx;
		margin-right: 10rpx;
		background-color: #ebedf0;
		border-radius: 10rpx;
		font-size: 32rpx;
		color: #333;
	}
</style>